/*
 * @Author: your name
 * @Date: 2020-07-29 17:11:52
 * @LastEditTime: 2020-09-24 10:37:10
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /amp-ec100/iot/app.js
 */
console.log('iot: testing iot...');
var iot = require('iot');
var gpio = require('gpio');
var i2c = require('i2c');
var network = require('network');

var net = network.openNetWorkClient();

/* 设备三元组信息获取请参考common目录下的iot组件说明 */
var productKey = 'productKey'; /* your productKey */
var deviceName = 'deviceName'; /* your deviceName */
var deviceSecret = 'deviceSecret'; /* your deviceSecret */

/** 初始化温度传感器lm75 */
var lm75 = i2c.open({
    id: 'I2C1',
    success: function () {
        console.log('bmp280 sensor open success')
    },
    fail: function () {
        console.log('bmp280 sensor open failed')
    }
});

/** 初始化led port */
var led1 = gpio.open({
    id: 'D1',
});

led1.writeValue(1);

var led2 = gpio.open({
    id: 'D2',
});

led1.writeValue(1);

var led3 = gpio.open({
    id: 'D3',
});

led3.writeValue(1);

var led4 = gpio.open({
    id: 'D4',
});

led4.writeValue(1);

/** 打开蜂鸣器 */
var beep = gpio.open({
    id: 'D5',
    success: function () {
        console.log('gpio: open beep success')
    },
    fail: function () {
        console.log('gpio: open beep failed')
    }
});

beep.writeValue(1);

// 获取传感器数据
function lm75tmpGet() {
	var temp;
	var sig = 1;
	var regval = lm75.readMem(0x00, 2);
	console.log('read regval is ' + regval);
	if (!regval) {
		return;
	}
	var tempAll = (regval[0] << 8) + regval[1];
	console.log('tempAll is ' + tempAll);

	if (regval[0] & 0x80 != 0) {
		tempAll = ~(tempAll) + 1;
		sig = -1;
	}

	tempAll = tempAll >> 5;
	console.log('tempAll final data ' + tempAll);
	temp = tempAll * 0.125 * sig;

	return temp;
}

// 业务逻辑
// 3秒采集并上传一次温度数据
function reportDatatoCloud() {
    setInterval(function () {
        temp = lm75tmpGet();
        device.postProps(JSON.stringify({
            IndoorTemperature: temp
        }));
        console.log('lm75 data is ' + temp);
    }, 3000);
}


// 构建物联网连接实例
var device;
net.on('connect', function () {
    device = iot.device({
        productKey: productKey,
        deviceName: deviceName,
        deviceSecret: deviceSecret
    });

    device.on('connect', function () {
        console.log('iot: [success] iot.on(\'connect\')');
        led2.writeValue(0);

        /* 云端设置属性事件 */
        device.onProps(function (res) {
            console.log('cloud req msg_id is ' + res.msg_id);
            console.log('cloud req params_len is ' + res.params_len);
            console.log('cloud req params is ' + res.params);

            var payload = JSON.parse(res.params);

            if (payload.LightSwitch == 1) {
                led1.writeValue(1);
                device.postProps(JSON.stringify({
                    LightSwitch: 1
                }));
            }
            if (payload.LightSwitch == 0) {
                led1.writeValue(0);
                device.postProps(JSON.stringify({
                    LightSwitch: 0
                }));
            }
        });

        /* 云端下发服务事件 */
        device.onService(function (res) {
            console.log('received cloud msg_id is ' + res.msg_id);
            console.log('received cloud service_id is ' + res.service_id);
            console.log('received cloud params_len is ' + res.params_len);
            console.log('received cloud params is ' + res.params);
        });

        reportDatatoCloud();
    });

    /* 网络断开事件 */
    device.on('disconnect', function () {
        console.log('disconnect ');
    });

    /* mqtt消息 */
    device.on('message', function (res) {
        console.log('mqtt message')
        console.log('mqtt topic is ' + res.topic);
        console.log('mqtt payload is ' + res.payload);
    })

    /* 关闭连接事件 */
    device.on('end', function () {
        console.log('iot client just closed');
    });

    /* 发生错误事件 */
    device.on('error', function (err) {
        console.log('error ' + err);
    });
})